package com.speed.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.jfinal.kit.StrKit;

public enum SmsFactory {

	INSTANCE;

	private List<String> mobiles = new ArrayList<String>();

	public void addMobileNo(String mobile) {
		mobiles.add(mobile);
	}

	private String getMobilesStr() {
		if (mobiles.isEmpty()) {
			return "";
		}
		// 第一个手机号码
		StringBuffer allMp = new StringBuffer(mobiles.get(0));
		for (int i = 1; i < mobiles.size(); i++) {
			allMp.append("," + mobiles.get(i));
		}
		return allMp.toString();
	}

	public void sendAll(String mobiles, String content) {
		if (mobiles == null) {
			String mobilesStr = getMobilesStr();
			if (StrKit.isBlank(mobilesStr)) {
				return;
			}
			send(mobilesStr, content);
		}else{
			if(StrKit.isBlank(mobiles)){
				return ;
			}
			send(mobiles, content);
		}
	}

	public void send(String mobile, String content) {
		
		System.out.println("短信内容:");
		System.out.println(content);
		String smsUrl = "https://smsapi.ums86.com:9600/sms/Api/Send.do";

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(smsUrl);
		post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
		post.addParameter(new NameValuePair("SpCode", "230490"));
		post.addParameter(new NameValuePair("LoginName", "admin3"));
		post.addParameter(new NameValuePair("Password", "dgqc8920"));
		post.addParameter(new NameValuePair("MessageContent", content));
		post.addParameter(new NameValuePair("UserNumber", mobile));
		System.out.println("000"+GenerationSerialNo.generFullNo());
		post.addParameter(new NameValuePair("SerialNumber", "000"+GenerationSerialNo.generFullNo()));
		post.addParameter(new NameValuePair("ScheduleTime", ""));
		post.addParameter(new NameValuePair("ExtendAccessNum", ""));
		post.addParameter(new NameValuePair("f", "1"));

		try {
			client.executeMethod(post);
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Header[] headers = post.getResponseHeaders();
		int statusCode = post.getStatusCode();
		System.out.println("statusCode:" + statusCode);
		for (Header h : headers) {
			System.out.println(h.toString());
		}
		// 获取内容 content
		String result;
		try {
			result = new String(post.getResponseBodyAsString().getBytes("GBK"));
			System.out.println(result);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		post.releaseConnection();
	}
}
